class ContactsController < ApplicationController
  def index
    @title = "Contacts"
    @contacts = Contact.find(:all, :order => "created_at DESC")
  end

  def new
    @title = "Add Contact"
    @contact = Contact.create(params[:contact]);
    if @contact.valid?
      flash[:info] = { :title => "#{@contact.name} has been added" }
      redirect_to :action => "index"
    else
      render :action => "create"
    end
  end

  def create
    @title = "Add Contact"
    @contact = Contact.new
  end

  def edit
    if Contact.exists? params[:id]
      @contact = Contact.find_by_id(params[:id])
      @title = "Edit Contact: #{@contact.name}"
    else
      flash[:info] = { 
        :title => "Contact Not Found",
        :explanation => "The contact you requested could not be edited.",
        :type => "error"
      }
      redirect_to :action => "index"
    end
  end

  def update
    @contact = Contact.find_by_id(params[:id])
    unless @contact
      flash[:info] = { 
        :title => "Contact Not Found",
        :explanation => "The contact you requested could not be deleted.",
        :type => "error"
      }
      redirect_to :action => "index"
      return
    end
    
    @contact.update_attributes params[:contact]
    if @contact.valid?
      @contact.save
      flash[:info] = { :title => "#{@contact.name} has been updated"}
      redirect_to :action => "index"
    else
      render :action => "edit"
    end
  end

  def destroy
    contact = Contact.find_by_id(params[:id])
    unless contact.nil?
      flash[:info] = { :title => "#{contact.name} has been deleted"}
      contact.destroy
    else
      flash[:info] = { 
        :title => "Contact Not Found",
        :explanation => "The contact you requested could not be deleted.",
        :type => "error"
      }
    end
    
    redirect_to :action => "index"
  end

  def search
    @contacts = Contact.search(params[:query])
    render :action => 'index'
  end
end
